using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Lucene.Net.Search;
using Microsoft.AspNetCore.Hosting;
using MongoDB.Driver.Core.WireProtocol.Messages.Encoders;
using Npoi.Mapper;
using NPOI.POIFS.Properties;
using NPOI.Util;
using Publicuse.Application;
using Publicuse.Autofac;
using Publicuse.Cache;
using Publicuse.Entity;
using Publicuse.Entity.AttributeUtil;
using Publicuse.Export;
using Publicuse.Interface;
using Publicuse.Util;
using ServiceStack;
using SqlSugar;
using Ubiety.Dns.Core;

namespace Publicuse.Appication
{
  public class MenuApplication
  {
    private static BaesApplication baseApplication;
    private static MenuApplication userApplication;

    public static MenuApplication GetApplication(ServiceContainer container)
    {
      baseApplication = new BaesApplication(container);
      return userApplication;
    }

    static MenuApplication()
    {
      userApplication = new MenuApplication();
    }

    /// <summary>
    /// 获取菜单详细信息
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetDetail(int Id)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var list = baseApplication.mySqlSugar.QueryByExpression<Menu>(o => o.Id == Id, out var msg);
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var menu = list.FirstOrDefault();
          result.data = menu;
        }
        result.msg = msg;
        return result;
      });
    }

    /// <summary>
    /// 获取菜单信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetList(Menu query)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var tableName = TableAtributeUtil.GetTable<Menu>();
        string sql = query.GetQueryString<Menu>(null);
        MenuQuery MenuQuery = new MenuQuery()
        {
          tableName = tableName,
          sqlWhere = sql,
          sortFile = query.sortFile,
          sortType = query.sortType,
          files = "*",
          pageIndex = query.pageIndex,
          pageSize = 10000,
        };
        baseApplication
          .GetList<Menu>(
            MenuQuery,
            false,
            (list, total) =>
            {
              result.count = total;
              list = list.OrderBy(o => o.amoduleIndex).ToList();

              List<Menu> menulist = new List<Menu>();
              if (list != null && list.Count > 0)
              {
                var modulelist = list.Where(o => o.aType == 1);
                if (modulelist != null && modulelist.Count() > 0)
                {
                  modulelist.ForEach(item =>
                  {
                    var childlist = list.Where(o => o.aType == 2 && o.aParentId == item.Id);
                    if (childlist != null && childlist.Count() > 0)
                    {
                      item.children = new List<Menu>();
                      childlist.ForEach(child =>
                      {
                        var childlistb = list.Where(o => o.aType == 3 && o.aParentId == child.Id);
                        if (childlistb != null && childlistb.Count() > 0)
                        {
                          child.children = new List<Menu>();
                          childlistb.ForEach(childb =>
                          {
                            childb.amoduleIndex = childb.abIndex;
                            child.children.Add(childb);
                          });
                          child.children = child.children.OrderBy(o => o.abIndex).ToList();
                        }
                        item.children.Add(child);
                      });
                      item.children = item.children.OrderBy(o => o.amoduleIndex).ToList();
                    }
                    menulist.Add(item);
                  });
                }
              }
              result.data = menulist;
            }
          )
          .GetAwaiter()
          .GetResult();
        return result;
      });
    }

    /// <summary>
    /// 根据当前登录账号的菜单权限资源
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> GetMenuPermission()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var token = HttpContextExtendBase.GetTokenStr();
        UserRouteData userRouteData = LoginCache.GetLoginCache.GetUserRouteData(token);
        if (userRouteData != null)
        {
          result.data = userRouteData;
          result.count = 1;
        }
        else
        {
          result.msg = "未获取到用户菜单权限信息";
        }
        return result;
      });
    }

    /// <summary>
    /// 根据用户编号获取对应菜单权限
    /// </summary>
    /// <param name="uId"></param>
    /// <returns></returns>
    public async Task<CommonResult> getMenuByUserId(int uId)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var token = HttpContextExtendBase.GetTokenStr();
        List<AuthorityMenu>? menu = new List<AuthorityMenu>();
        if (!string.IsNullOrEmpty(token))
        {
          var list = LoginCache.GetLoginCache.GetLoginMenu(token);
          if (list != null && list.Count > 0)
          {
            menu =
              list.MapToList<AuthorityMenu, Menu>(o =>
              {
                o.ForMember(d => d.aisCURD, opt => opt.MapFrom(s => s.aisCURD));
                o.ForMember(d => d.id, opt => opt.MapFrom(s => s.Id));
                o.ForMember(d => d.menuName, opt => opt.MapFrom(s => s.aName));
                o.ForMember(d => d.code, opt => opt.MapFrom(s => s.aCode));
                o.ForMember(d => d.fatherId, opt => opt.MapFrom(s => s.aParentId));
                o.ForMember(
                  d => d.orderNum,
                  opt =>
                    opt.MapFrom(s =>
                      s.aType == 2
                        ? s.amoduleIndex
                        : s.aType == 1
                          ? s.amoduleIndex
                          : s.abIndex
                    )
                );
                o.ForMember(d => d.path, opt => opt.MapFrom(s => s.ahtmlUrl));
                o.ForMember(d => d.menuType, opt => opt.MapFrom(s => s.aType == 3 ? "F" : "C"));
                o.ForMember(d => d.visible, opt => opt.MapFrom(s => s.aType == 3 ? false : true));
                o.ForMember(d => d.status, opt => opt.MapFrom(s => s.status == 1 ? true : false));
                o.ForMember(
                  d => d.icon,
                  opt => opt.MapFrom(s => s.aType == 3 ? s.abIcon : s.ahtmlIcon)
                );
                o.ForMember(d => d.alIcon, opt => opt.MapFrom(s => string.Empty));
              }) as List<AuthorityMenu>;
            result.count = menu.Count;
            result.data = menu;
          }
        }
        return result;
      });
    }

    /// <summary>
    /// 根据key获取对应名称
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResult> GetMenuAll()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        result.data = LoginCache.GetLoginCache.GetMenuAll();
        return result;
      });
    }

    /// <summary>
    /// 获取树形数据信息
    /// </summary>
    /// <param name="aName"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetTreeList(string pid)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Menu>();
        var sqlwhere = " where 1=1 ";
        var sql = $"select * from {table} {sqlwhere};";
        var data = baseApplication.mySqlSugar.Query<Menu>(sql, out var msg);
        result.msg = msg;
        if (string.IsNullOrEmpty(msg))
        {
          if (data.Count > 0)
          {
            List<MenuTree> MenuTrees = new List<MenuTree>();
            var modulelist = data.Where(o => o.aType == 1);
            foreach (var item in modulelist)
            {
              MenuTree MenuTree = item.AutoFormModel<MenuTree, Menu>(o =>
                o.ForMember(d => d.key, opt => opt.MapFrom(s => s.Id))
              );

              var modulelistb = data.Where(o => o.aParentId == MenuTree.key);
              if (modulelistb.Count() > 0)
              {
                MenuTree.havechildren = true;
              }
              List<MenuTree> trees = new List<MenuTree>();
              modulelistb = data.Where(o => o.aParentId == MenuTree.key);
              foreach (var itemb in modulelistb)
              {
                MenuTree MenuTreeb = itemb.AutoFormModel<MenuTree, Menu>(o =>
                  o.ForMember(d => d.key, opt => opt.MapFrom(s => s.Id))
                );

                AddChildren(MenuTreeb, data);
                trees.Add(MenuTreeb);
              }
              MenuTree.children = new List<MenuTree>();
              MenuTree.children = trees;

              MenuTrees.Add(MenuTree);
            }
            result.count = MenuTrees.Count;
            result.data = MenuTrees;
          }
        }
        return result;
      });
    }

    /// <summary>
    /// 根据菜单名称获取所有信息
    /// </summary>
    /// <param name="aName"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetListb(string aName)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Menu>();
        var sql = $"select Id,aName from {table} where status<>-9 ";
        if (!string.IsNullOrEmpty(aName))
        {
          sql += $" and aName like '%{aName}%' ";
        }
        sql += " order by Id desc; ";
        var list = baseApplication.mySqlSugar.Query<Menu>(sql, out var msg);
        result.msg = msg;
        result.data = list;
        return result;
      });
    }

    /// <summary>
    /// 绑定用户菜单信息
    /// </summary>
    /// <param name="saveUserRole"></param>
    /// <returns></returns>
    public async Task<CommonResult> SaveUserResource(SaveUserRole saveUserRole)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var user = TableAtributeUtil.GetTable<User>();
        var userrole = TableAtributeUtil.GetTable<UserRole>();
        var userresource = TableAtributeUtil.GetTable<URPermission>();
        StringBuilder stringBuilder = new StringBuilder();
        foreach (var uId in saveUserRole.uids.Split(','))
        {
          if (string.IsNullOrEmpty(uId.Trim()))
          {
            continue;
          }
          var sql = $"select * from {user} a where a.uCode='{uId}' and a.status<>-9 ; ";
          var userdata = baseApplication.mySqlSugar.Query<User>(sql, out var msg);
          if (string.IsNullOrEmpty(msg) && userdata != null && userdata.Count > 0)
          {
            var uIdb = userdata.FirstOrDefault().Id;
            sql = $"select b.rids  from {userrole} b where b.uId='{uIdb}'; ";
            var list = baseApplication.mySqlSugar.Query<UserRole>(sql, out msg);
            if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
            {
              foreach (var item in list)
              {
                foreach (var rid in item.rids.Split(','))
                {
                  sql =
                    $"select aIds,Id from {userresource} where uId='{uIdb}' and rId='{rid}' and status<>-9; ";
                  var listb = baseApplication.mySqlSugar.Query<URPermission>(sql, out var msgb);
                  if (string.IsNullOrEmpty(msgb) && listb != null && listb.Count > 0)
                  {
                    foreach (var itemc in listb)
                    {
                      var newaIds = itemc.aIds + "," + saveUserRole.aids;
                      sql = $"update {userresource} set aIds='{newaIds}' where Id='{itemc.Id}'; ";
                      baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
                      if (!string.IsNullOrEmpty(msg))
                      {
                        stringBuilder.Append(msg + "|" + sql);
                      }
                    }
                  }
                  else
                  {
                    URPermission uRPermission = new URPermission()
                    {
                      uId = uIdb,
                      rId = rid.GetIntValue(),
                      status = 1,
                      aIds = saveUserRole.aids,
                      cTime = DateTime.Now
                    };
                    baseApplication.mySqlSugar.Insert<URPermission>(uRPermission, out msg);
                    if (!string.IsNullOrEmpty(msg))
                    {
                      stringBuilder.Append(msg + "|bb");
                    }
                  }
                }
              }
            }
          }
        }
        result.msg = stringBuilder.ToString();
        UserAuthorCache.AddURMcache(baseApplication.mySqlSugar, true, true);
        return result;
      });
    }

    /// <summary>
    /// 根据树形菜单信息
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetTreeListb()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Menu>();
        var sql = $"select * from {table} where status=1;";
        var list = baseApplication.mySqlSugar.Query<Menu>(sql, null, out var msg);
        List<MenuTreeb> MenuTrees = new List<MenuTreeb>();
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          list = list.OrderBy(o => o.amoduleIndex).ToList();
          var modulelist = list.Where(o => o.aType == 1);
          if (modulelist != null && modulelist.Count() > 0)
          {
            modulelist.ForEach(item =>
            {
              var childlist = list.Where(o => o.aType == 2 && o.aParentId == item.Id);
              MenuTreeb menuTreeb = new MenuTreeb()
              {
                title = item.aName,
                value = item.Id.ToString(),
                sort = item.amoduleIndex
              };
              if (childlist != null && childlist.Count() > 0)
              {
                menuTreeb.children = new List<MenuTreeb>();
                childlist.ForEach(child =>
                {
                  MenuTreeb menuTreec = new MenuTreeb()
                  {
                    title = child.aName,
                    value = child.Id.ToString(),
                    sort = child.amoduleIndex
                  };
                  var childlistb = list.Where(o => o.aType == 3 && o.aParentId == child.Id);
                  if (childlistb != null && childlistb.Count() > 0)
                  {
                    menuTreec.children = new List<MenuTreeb>();
                    childlistb.ForEach(childb =>
                    {
                      MenuTreeb menuTreed = new MenuTreeb()
                      {
                        title = childb.aName,
                        value = childb.Id.ToString(),
                        sort = childb.abIndex
                      };
                      menuTreec.children.Add(menuTreed);
                    });
                    menuTreeb.children = menuTreeb.children.OrderBy(o => o.sort).ToList();
                  }
                  menuTreeb.children.Add(menuTreec);
                });
                menuTreeb.children = menuTreeb.children.OrderBy(o => o.sort).ToList();
              }
              MenuTrees.Add(menuTreeb);
            });
          }
        }
        result.count = MenuTrees.Count;
        result.data = MenuTrees;
        return result;
      });
    }

    /// <summary>
    /// 根据角色编号获取绑定菜单树形数据信息
    /// </summary>
    /// <param name="rId"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetTreeListc(string rId)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Menu>();
        var sql = $"select * from {table} where status=1;";
        var list = baseApplication.mySqlSugar.Query<Menu>(sql, null, out var msg);
        List<MenuTreec> MenuTrees = new List<MenuTreec>();
        List<string> expandedKeys = new List<string>();
        if (string.IsNullOrEmpty(msg) && list != null && list.Count > 0)
        {
          var roleMenus = UserAuthorCache.GetRoleRescache();
          var havelist = roleMenus.Where(o => o.rId == rId.GetLongValue());
          List<string> aidlist = new List<string>();
          if (havelist != null && havelist.Count() > 0)
          {
            aidlist = havelist.Select(o => o.aIds).ToList();
          }
          list = list.OrderBy(o => o.amoduleIndex).ToList();
          var modulelist = list.Where(o => o.aType == 1);
          if (modulelist != null && modulelist.Count() > 0)
          {
            modulelist.ForEach(item =>
            {
              var childlist = list.Where(o => o.aType == 2 && o.aParentId == item.Id);
              MenuTreec menuTreeb = new MenuTreec()
              {
                title = item.aName,
                key = item.Id.ToString(),
                sort = item.amoduleIndex,
                isexpand = true
              };
              if (aidlist.Any(o => o == item.Id.ToString()))
              {
                menuTreeb.ischecked = true;
              }
              if (childlist != null && childlist.Count() > 0)
              {
                expandedKeys.Add(item.Id.ToString());
                menuTreeb.children = new List<MenuTreec>();
                childlist.ForEach(child =>
                {
                  MenuTreec menuTreec = new MenuTreec()
                  {
                    title = child.aName,
                    key = child.Id.ToString(),
                    sort = child.amoduleIndex,
                    isexpand = true
                  };
                  if (aidlist.Any(o => o == child.Id.ToString()))
                  {
                    menuTreec.ischecked = true;
                  }
                  var childlistb = list.Where(o => o.aType == 3 && o.aParentId == child.Id);
                  if (childlistb != null && childlistb.Count() > 0)
                  {
                    menuTreec.children = new List<MenuTreec>();
                    childlistb.ForEach(childb =>
                    {
                      MenuTreec menuTreed = new MenuTreec()
                      {
                        title = childb.aName,
                        key = childb.Id.ToString(),
                        sort = childb.abIndex
                      };
                      if (aidlist.Any(o => o == childb.Id.ToString()))
                      {
                        menuTreed.ischecked = true;
                        menuTreed.isexpand = true;
                      }
                      menuTreec.children.Add(menuTreed);
                    });
                    menuTreeb.children = menuTreeb.children.OrderBy(o => o.sort).ToList();
                  }
                  menuTreeb.children.Add(menuTreec);
                });
                menuTreeb.children = menuTreeb.children.OrderBy(o => o.sort).ToList();
              }
              MenuTrees.Add(menuTreeb);
            });
          }
        }
        result.count = MenuTrees.Count;
        result.data = MenuTrees;
        result.datab = expandedKeys;
        return result;
      });
    }

    /// <summary>
    /// 根据树形菜单信息
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetTreeList()
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        var table = TableAtributeUtil.GetTable<Menu>();
        var sql = $"select * from {table} where status=1;";
        var data = baseApplication.mySqlSugar.Query<Menu>(sql, null, out var msg);
        List<MenuTree> MenuTrees = new List<MenuTree>();
        if (string.IsNullOrEmpty(msg))
        {
          if (data.Count > 0)
          {
            foreach (var item in data)
            {
              MenuTree MenuTree = item.AutoFormModel<MenuTree, Menu>(o =>
                o.ForMember(d => d.key, opt => opt.MapFrom(s => s.Id))
              );

              var modulelistb = data.Where(o => o.aParentId == MenuTree.key);
              if (modulelistb.Count() > 0)
              {
                MenuTree.havechildren = true;
              }

              MenuTrees.Add(MenuTree);
            }
          }
        }
        result.count = MenuTrees.Count;
        result.data = MenuTrees;
        return result;
      });
    }

    /// <summary>
    /// 递归循环设置Tree值
    /// </summary>
    /// <param name="tree"></param>
    /// <param name="list"></param>
    private static void AddChildren(MenuTree tree, List<Menu> list)
    {
      List<MenuTree> trees = new List<MenuTree>();
      var modulelist = list.Where(o => o.aParentId == tree.key);
      foreach (var itemb in modulelist)
      {
        MenuTree MenuTreeb = itemb.AutoFormModel<MenuTree, Menu>(o =>
          o.ForMember(d => d.key, opt => opt.MapFrom(s => s.Id))
        );
        trees.Add(MenuTreeb);
        var modulelistb = list.Where(o => o.aParentId == MenuTreeb.key);
        if (modulelistb.Count() > 0)
        {
          AddChildren(MenuTreeb, list);
        }
        tree.havechildren = true;
      }
      tree.children = new List<MenuTree>();
      tree.children = trees;
    }

    /// <summary>
    /// 获取菜单信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetMenuAll(MenuQuery query)
    {
      var tableName = TableAtributeUtil.GetTable<Menu>();
      string sql = string.Format(" where 1=1 and status<>-9 ");

      sql += string.Format(" and aType <>3 ", query.aType);

      if (!string.IsNullOrEmpty(query.aName))
      {
        sql += string.Format(" and aName like '%{0}%' ", query.aName);
      }
      if (query.status != -1 && query.status != -9)
      {
        sql += string.Format(" and status ={0} ", query.status);
      }
      if (query.status == -9)
      {
        sql += string.Format(" and status ={0} ", query.status);
      }

      MenuQuery MenuQuery = new MenuQuery()
      {
        tableName = tableName,
        sqlWhere = sql,
        sortFile = "Id",
        sortType = "desc",
        files = "*",
        pageIndex = 1,
        pageSize = 2000,
      };
      return await baseApplication.GetList<Menu>(MenuQuery);
    }

    /// <summary>
    /// 获取菜单模块信息列表
    /// </summary>
    /// <param name="query"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetMenuModuleList(MenuQuery query)
    {
      var tableName = TableAtributeUtil.GetTable<Menu>();
      string sql = string.Format(" where 1=1 and aType<>3 and status<>-9 ");
      MenuQuery MenuQuery = new MenuQuery()
      {
        tableName = tableName,
        sqlWhere = sql,
        sortFile = "Id",
        sortType = "desc",
        files = "*",
        pageIndex = query.pageIndex,
        pageSize = 250,
      };
      string msg = string.Empty;
      return await baseApplication.GetList<Menu>(MenuQuery);
    }

    /// <summary>
    /// 检查菜单名称是否存在
    /// </summary>
    /// <param name="aName"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckMenuName(
      string aName,
      string loginUserCode,
      string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Menu>(
        BusinessType.menu,
        BusinessLogType.writeLogToDataBase,
        o => o.aName == aName && o.status != -9,
        "检查菜单名称是否存在",
        Id
      );
    }

    /// <summary>
    /// 检查菜单编码是否存在
    /// </summary>
    /// <param name="aCode"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task<CommonResult> CheckMenuCode(
      string aCode,
      string loginUserCode,
      string Id = ""
    )
    {
      return await baseApplication.CheckDataExists<Menu>(
        BusinessType.menu,
        BusinessLogType.writeLogToDataBase,
        o => o.aCode == aCode && o.status != -9,
        "检查菜单编码是否存在",
        Id
      );
    }

    /// <summary>
    /// 获取用户绑定角色菜单信息
    /// </summary>
    /// <param name="uId"></param>
    /// <param name="rId"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetUserResourceList(
      string uId,
      string rId,
      string loginUserCode
    )
    {
      return await baseApplication.DoAction(
        BusinessType.menu,
        BusinessActionType.query,
        BusinessLogType.NoWrite,
        loginUserCode,
        uId + "|" + rId,
        "获取用户绑定角色菜单信息",
        (baseService) =>
        {
          CommonResult result = new CommonResult();
          var tableName = TableAtributeUtil.GetTable<Menu>();
          string msg = string.Empty;
          MenuQuery queryb = new MenuQuery()
          {
            tableName = tableName,
            sqlWhere = " where 1=1 and status=1 ",
            sortFile = "Id",
            sortType = "asc",
            pageIndex = 1,
            pageSize = 100000,
            files = "*"
          };
          var LoginCode = HttpContextExtendBase.GetLoginCode();
          if (string.Compare(LoginCode, "ajng", true) != 0)
          {
            var LoginRsId = HttpContextExtendBase.GetLoginRsId();
            var LoginrId = HttpContextExtendBase.GetLoginrId();
            var LoginuId = HttpContextExtendBase.GetLoginuId();
            var table = TableAtributeUtil.GetTable<URPermission>();
            var sqlb = $"select aIds from {table} where uId='{LoginuId}' and rId='{LoginrId}';";
            var listb = baseApplication.mySqlSugar.Query<URPermission>(sqlb, out msg);
            List<string> aidlist = new List<string>();
            if (string.IsNullOrEmpty(msg) && listb != null && listb.Count > 0)
            {
              aidlist = listb.Select(o => o.aIds).ToList();
            }
            var tableb = TableAtributeUtil.GetTable<RoleResource>();
            var sqlc = $"select aIds from {tableb} where rId='{LoginrId}';";
            var listc = baseApplication.mySqlSugar.Query<RoleResource>(sqlc, out msg);
            if (string.IsNullOrEmpty(msg) && listc != null && listc.Count > 0)
            {
              var aidlistc = listc.Select(o => o.aIds).ToList();
              foreach (var item in aidlistc)
              {
                aidlist.Add(item);
              }
            }
            if (aidlist.Count > 0)
            {
              List<Menu> listd = new List<Menu>();
              var Menu = TableAtributeUtil.GetTable<Menu>();
              var sqld = $"select * from {Menu} where Id in({String.Join(",", aidlist)});";
              var havelist = baseApplication.mySqlSugar.Query<Menu>(sqld, out msg);
              if (string.IsNullOrEmpty(msg) && havelist != null && havelist.Count > 0)
              {
                foreach (var item in havelist)
                {
                  var rsId = $" and FIND_IN_SET('{LoginRsId}',sysmoduleid) ";
                  var sqlall = $"select * from {Menu} where status<>-9 {rsId};";
                  List<Menu> alllist = baseApplication.mySqlSugar.Query<Menu>(sqlall, out msg);
                  var parentdata = alllist.Where(o => o.Id == item.aParentId).ToList();
                  if (string.IsNullOrEmpty(msg) && parentdata.Count > 0)
                  {
                    if (!listd.Any(o => o.Id == parentdata.FirstOrDefault().Id))
                    {
                      listd.Add(parentdata.FirstOrDefault());
                      var parentdatab = alllist
                        .Where(o => o.Id == parentdata.FirstOrDefault().aParentId)
                        .ToList();
                      if (string.IsNullOrEmpty(msg) && parentdata.Count > 0)
                      {
                        AddParentData(
                          baseApplication.mySqlSugar,
                          parentdata.FirstOrDefault().aParentId,
                          ref listd,
                          alllist
                        );
                      }
                    }
                  }
                  listd.Add(item);
                }
                aidlist = listd.DistinctBy(o => o.Id).Select(o => o.Id.ToString()).ToList();
              }
            }
            queryb.sqlWhere +=
              $" and ( FIND_IN_SET('{LoginRsId}',sysmoduleid)) and Id in({String.Join(",", aidlist)})";
          }
          List<Menu> list = new List<Menu>();
          List<Menu> MenuExtend = new List<Menu>();
          long totalCount = 0;
          baseService.GetList(queryb, out msg, out list, out totalCount);
          if (list.Count > 0)
          {
            MenuExtend = list.MapToList<Menu, Menu>(o => { }) as List<Menu>;
            var pidlist = MenuExtend.Where(o => o.aType == 2).Select(o => o.aParentId).Distinct();
            var sqlb = $"select * from {tableName} where Id in({string.Join(",", pidlist)});";
            var listb = baseApplication.mySqlSugar.Query<Menu>(sqlb, out msg);
            if (string.IsNullOrEmpty(msg) && listb != null && listb.Count > 0)
            {
              var MenuExtendnew = listb.MapToList<Menu, Menu>(o => { }) as List<Menu>;
              foreach (var itemb in MenuExtendnew)
              {
                MenuExtend.Add(itemb);
              }
            }
          }
          tableName = TableAtributeUtil.GetTable<URPermission>();
          string sql = $"select aIds from {tableName} where uId='{uId}' and rId='{rId}';";
          var data = baseService.GetDataTable(sql, null, out msg);
          foreach (DataRow item in data.Rows)
          {
            var aIds = item["aIds"].ToString().Split(',');
            foreach (var authr in MenuExtend)
            {
              if (aIds.Any(o => o == authr.Id.ToString()))
              {
                authr.ischecked = true;
              }
            }
          }
          result.data = MenuExtend.DistinctBy(o => o.Id);
          return result;
        }
      );
    }

    private static void AddParentData(
      IMySqlSugarService mySqlBaseService,
      long pid,
      ref List<Menu> authorities,
      List<Menu> alllist
    )
    {
      var parentdata = alllist.Where(o => o.Id == pid).ToList();
      if (parentdata.Count > 0)
      {
        if (!authorities.Any(o => o.Id == parentdata.FirstOrDefault().Id))
        {
          authorities.Add(parentdata.FirstOrDefault());
        }
        AddParentData(
          mySqlBaseService,
          parentdata.FirstOrDefault().aParentId,
          ref authorities,
          alllist
        );
      }
    }

    /// <summary>
    /// 获取角色绑定菜单信息
    /// </summary>
    /// <param name="rId"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetRoleResourceList(string rId, string loginUserCode)
    {
      return await baseApplication.DoAction(
        BusinessType.menu,
        BusinessActionType.query,
        BusinessLogType.NoWrite,
        loginUserCode,
        rId,
        "获取角色绑定菜单信息",
        (baseService) =>
        {
          CommonResult result = new CommonResult();
          var tableName = TableAtributeUtil.GetTable<Menu>();
          string msg = string.Empty;
          MenuQuery queryb = new MenuQuery()
          {
            tableName = tableName,
            sqlWhere = "",
            sortFile = "Id",
            sortType = "asc",
            pageIndex = 1,
            pageSize = 100000,
            files = "*"
          };
          List<Menu> list = new List<Menu>();
          long totalCount = 0;
          baseService.GetList(queryb, out msg, out list, out totalCount);
          tableName = TableAtributeUtil.GetTable<RoleResource>();
          string sql = $"select aIds from {tableName} where rId=@rId;";
          var data = baseService.GetDataTable(sql, new { rId = rId }, out msg);
          foreach (DataRow item in data.Rows)
          {
            var aIds = item["aIds"].ToString().Split(',');
            foreach (var authr in list)
            {
              if (aIds.Any(o => o == authr.Id.ToString()))
              {
                authr.ischecked = true;
              }
            }
          }
          result.data = list;
          return result;
        }
      );
    }

    /// <summary>
    /// 新增修改菜单信息
    /// </summary>
    /// <param name="info"></param>
    /// <param name="_hostingEnvironment"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddOrUpdate(Menu info, IWebHostEnvironment _hostingEnvironment)
    {
      return await baseApplication.AddOrUpdate<Menu>(
        info,
        BusinessType.menu,
        BusinessLogType.writeLogToDataBase,
        (baseService) =>
        {
          CommonResult result = new CommonResult();
          var table = TableAtributeUtil.GetTable<Menu>();
          string msg = string.Empty;
          string sql = string.Empty;

          if (info.Id == 0)
          {
            if (info.aType == 3 && string.IsNullOrEmpty(info.aapiUrl))
            {
              var plist = baseApplication.mySqlSugar.QueryByExpression<Menu>(
                o => o.Id == info.aParentId,
                out msg
              );
              if (string.IsNullOrEmpty(msg) && plist != null && plist.Count() > 0)
              {
                var paCode = plist.FirstOrDefault().aCode;
                var newacode = info.aCode.Replace(paCode, "Check");
                info.aapiUrl = "api/" + paCode + "/" + newacode;
              }
            }
            var parentId = baseService.Insert(info, out msg);
            var tableName = TableAtributeUtil.GetTable<Menu>();
            sql =
              $"select aName,ahtmlUrl from {tableName} where status<>-9 and atype=2 and ahtmlUrl<>'';";
            var dataTable = baseService.GetDataTable(sql, null, out msg);
            if (string.IsNullOrEmpty(msg) && dataTable != null)
            {
              List<MenuSimple> simples = new List<MenuSimple>();
              foreach (DataRow item in dataTable.Rows)
              {
                var aName = item["aName"].ToString();
                var ahtmlUrl = item["ahtmlUrl"].ToString();
                simples.Add(new MenuSimple { ahtmlUrl = ahtmlUrl, aName = aName });
              }
              LoginCache.GetLoginCache.ClearMenu();
              LoginCache.GetLoginCache.AddMenu(DateTime.Now.ToString("yyyyMMddHHmmss"), simples);
            }
            if (info.aType == 2)
            {
              List<Menu> list = new List<Menu>();
              AddResourceToChildren(list, info, parentId, baseApplication.mySqlSugar);
            }
          }
          else
          {
            if (info.aType == 3 && string.IsNullOrEmpty(info.aapiUrl))
            {
              var plist = baseApplication.mySqlSugar.QueryByExpression<Menu>(
                o => o.Id == info.aParentId,
                out msg
              );
              if (string.IsNullOrEmpty(msg) && plist != null && plist.Count() > 0)
              {
                var paCode = plist.FirstOrDefault().aCode;
                var newacode = info.aCode.Replace(paCode, "Check");
                info.aapiUrl = "api/" + paCode + "/" + newacode;
              }
            }
            info.uTime = DateTime.Now;
            baseService.Update(info, out msg);
            var tableName = TableAtributeUtil.GetTable<Menu>();
            sql = $" where 1=1 and aParentId='{info.Id}' ";
            List<Menu> list = new List<Menu>();
            MenuQuery query = new MenuQuery()
            {
              tableName = tableName,
              sqlWhere = sql,
              sortFile = "Id",
              sortType = "asc",
              pageIndex = 1,
              pageSize = 100,
              files = "*"
            };

            long totalCount = 0;
            baseService.GetList<Menu>(query, out msg, out list, out totalCount);

            if (info.aType == 2)
            {
              AddResourceToChildren(list, info, info.Id, baseService);
            }
            sql =
              $"select aName,ahtmlUrl from {tableName} where status<>-9 and atype=2 and ahtmlUrl<>'';";
            var dataTable = baseService.GetDataTable(sql, null, out msg);
            if (string.IsNullOrEmpty(msg) && dataTable != null)
            {
              List<MenuSimple> simples = new List<MenuSimple>();
              foreach (DataRow item in dataTable.Rows)
              {
                var aName = item["aName"].ToString();
                var ahtmlUrl = item["ahtmlUrl"].ToString();
                simples.Add(new MenuSimple { ahtmlUrl = ahtmlUrl, aName = aName });
              }
              LoginCache.GetLoginCache.ClearMenu();
              LoginCache.GetLoginCache.AddMenu(DateTime.Now.ToString("yyyyMMddHHmmss"), simples);
            }
          }

          if (string.IsNullOrEmpty(msg))
          {
            QueryCacheUtil<Menu>.RemoveData(table);
            result.code = (int)CodeResult.success;
            result.msg = string.Empty;
            result.data = null;
            result.count = 0;
          }
          else
          {
            result.msg = msg;
          }
          return result;
        },
        null,
        (total) =>
        {
          UserAuthorCache.AddAuthorcache(baseApplication.mySqlSugar, true, true);
        }
      );
    }

    /// <summary>
    /// 绑定权限操作按钮菜单
    /// </summary>
    /// <param name="list"></param>
    /// <param name="info"></param>
    /// <param name="parentId"></param>
    /// <param name="baseService"></param>
    private static void AddResourceToChildren(
      List<Menu> list,
      Menu info,
      long parentId,
      IMySqlSugarService baseService
    )
    {
      var msgb = string.Empty;
      List<Menu> listadd = new List<Menu>();
      var res = info.aisCURD.Split(',');
      //info.aCode = info.aCode.FirstCharToUpper();
      if (res.Any(b => b == "1"))
      {
        Menu add = new Menu();
        add.aapiUrl = "api/" + info.aCode + "/" + "CheckAdd";
        add.status = 1;
        add.aName = info.aName.Replace("管理", "") + "新增";
        add.aParentId = parentId;
        add.ahtmlIcon = string.Empty;
        add.ahtmlUrl = string.Empty;
        add.aCode = info.aCode.FirstCharToUpper() + "Add";
        add.aType = 3;
        add.abIndex = 1;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == add.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          add.uTime = DateTime.Now;
          add.Id = havedata.FirstOrDefault().Id;
          add.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(add);
      }
      if (res.Any(b => b == "2"))
      {
        Menu delete = new Menu();
        delete.aapiUrl = "api/" + info.aCode + "/" + "CheckDelete";
        delete.status = 1;
        delete.aName = info.aName.Replace("管理", "") + "删除";
        delete.ahtmlIcon = string.Empty;
        delete.ahtmlUrl = string.Empty;
        delete.aParentId = parentId;
        delete.aCode = info.aCode + "Delete";
        delete.aType = 3;
        delete.abIndex = 2;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == delete.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          delete.uTime = DateTime.Now;
          delete.Id = havedata.FirstOrDefault().Id;
          delete.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(delete);
      }
      if (res.Any(b => b == "3"))
      {
        Menu update = new Menu();
        update.aapiUrl = "api/" + info.aCode + "/" + "CheckUpdate";
        update.status = 1;
        update.aName = info.aName.Replace("管理", "") + "修改";
        update.aParentId = parentId;
        update.ahtmlIcon = string.Empty;
        update.ahtmlUrl = string.Empty;
        update.aCode = info.aCode + "Update";
        update.aType = 3;
        update.abIndex = 3;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == update.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          update.uTime = DateTime.Now;
          update.Id = havedata.FirstOrDefault().Id;
          update.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(update);
      }
      if (res.Any(b => b == "4"))
      {
        Menu query = new Menu();
        query.aapiUrl = "api/" + info.aCode + "/" + "CheckGetList";
        query.status = 1;
        query.aName = info.aName.Replace("管理", "") + "查询";
        query.ahtmlIcon = string.Empty;
        query.ahtmlUrl = string.Empty;
        query.aParentId = parentId;
        query.aCode = info.aCode + "GetList";
        query.aType = 3;
        query.abIndex = 4;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == query.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          query.uTime = DateTime.Now;
          query.Id = havedata.FirstOrDefault().Id;
          query.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(query);
      }
      if (res.Any(b => b == "5"))
      {
        Menu import = new Menu();
        import.aapiUrl = "api/" + info.aCode + "/" + "CheckImport";
        import.status = 1;
        import.aName = info.aName.Replace("管理", "") + "导入";
        import.ahtmlIcon = string.Empty;
        import.ahtmlUrl = string.Empty;
        import.aParentId = parentId;
        import.aCode = info.aCode + "Import";
        import.aType = 3;
        import.abIndex = 5;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == import.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          import.uTime = DateTime.Now;
          import.Id = havedata.FirstOrDefault().Id;
          import.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(import);
      }
      if (res.Any(b => b == "6"))
      {
        Menu export = new Menu();
        export.aapiUrl = "api/" + info.aCode + "/" + "CheckExport";
        export.status = 1;
        export.aName = info.aName.Replace("管理", "") + "导出";
        export.ahtmlIcon = string.Empty;
        export.ahtmlUrl = string.Empty;
        export.aParentId = parentId;
        export.aCode = info.aCode + "Export";
        export.aType = 3;
        export.abIndex = 6;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == export.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          export.uTime = DateTime.Now;
          export.Id = havedata.FirstOrDefault().Id;
          export.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(export);
      }
      if (res.Any(b => b == "7"))
      {
        Menu down = new Menu();
        down.aapiUrl = "api/" + info.aCode + "/" + "CheckDown";
        down.status = 1;
        down.aName = info.aName.Replace("管理", "") + "下载导入模板";
        down.ahtmlIcon = string.Empty;
        down.ahtmlUrl = string.Empty;
        down.aParentId = parentId;
        down.aCode = info.aCode + "Down";
        down.aType = 3;
        down.abIndex = 7;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == down.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          down.uTime = DateTime.Now;
          down.Id = havedata.FirstOrDefault().Id;
          down.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(down);
      }
      if (res.Any(b => b == "8"))
      {
        Menu upload = new Menu();
        upload.aapiUrl = "api/" + info.aCode + "/" + "CheckUpload";
        upload.status = 1;
        upload.aName = info.aName.Replace("管理", "") + "上传文件";
        upload.aParentId = parentId;
        upload.ahtmlIcon = string.Empty;
        upload.ahtmlUrl = string.Empty;
        upload.aCode = info.aCode + "Upload";
        upload.aType = 3;
        upload.abIndex = 8;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == upload.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          upload.uTime = DateTime.Now;
          upload.Id = havedata.FirstOrDefault().Id;
          upload.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(upload);
      }
      if (res.Any(b => b == "9"))
      {
        Menu audit = new Menu();
        audit.aapiUrl = "api/" + info.aCode + "/" + "CheckAudit";
        audit.status = 1;
        audit.aName = info.aName.Replace("管理", "") + "审核";
        audit.aParentId = parentId;
        audit.ahtmlIcon = string.Empty;
        audit.ahtmlUrl = string.Empty;
        audit.aCode = info.aCode + "Audit";
        audit.aType = 3;
        audit.abIndex = 9;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == audit.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          audit.uTime = DateTime.Now;
          audit.Id = havedata.FirstOrDefault().Id;
          audit.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(audit);
      }
      if (res.Any(b => b == "10"))
      {
        Menu roleresource = new Menu();
        roleresource.aapiUrl = "api/" + info.aCode + "/" + "CheckRoleResource";
        roleresource.status = 1;
        roleresource.aName = info.aName.Replace("管理", "") + "角色菜单";
        roleresource.aParentId = parentId;
        roleresource.ahtmlIcon = string.Empty;
        roleresource.ahtmlUrl = string.Empty;
        roleresource.aCode = info.aCode + "RoleResource";
        roleresource.aType = 3;
        roleresource.abIndex = 10;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == roleresource.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          roleresource.uTime = DateTime.Now;
          roleresource.Id = havedata.FirstOrDefault().Id;
          roleresource.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(roleresource);
      }
      if (res.Any(b => b == "11"))
      {
        Menu roleresource = new Menu();
        roleresource.aapiUrl = "api/" + info.aCode + "/" + "CheckRecyclebin";
        roleresource.status = 1;
        roleresource.aName = info.aName.Replace("管理", "") + "回收站";
        roleresource.aParentId = parentId;
        roleresource.ahtmlIcon = string.Empty;
        roleresource.ahtmlUrl = string.Empty;
        roleresource.aCode = info.aCode + "Recyclebin";
        roleresource.aType = 3;
        roleresource.abIndex = 10;
        var havedata = list.Where(o => o.aapiUrl.ToLower() == roleresource.aapiUrl.ToLower());
        if (havedata.Count() > 0)
        {
          roleresource.uTime = DateTime.Now;
          roleresource.Id = havedata.FirstOrDefault().Id;
          roleresource.cTime = havedata.FirstOrDefault().cTime;
        }
        listadd.Add(roleresource);
      }
      foreach (var item in listadd)
      {
        if (info.status == 1)
        {
          item.isShow = "是";
        }
        else
        {
          item.isShow = "否";
        }

        if (item.Id > 0)
          baseService.Update(item, out msgb);
        else
          baseService.Insert(item, out msgb);
      }
    }

    /// <summary>
    /// 删除菜单信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResult> Delete(string Id, string loginUserCode, string type)
    {
      return await baseApplication.Delete<Menu>(
        Id,
        loginUserCode,
        type,
        BusinessType.menu,
        (a, b, info) =>
        {
          return info.aName;
        },
        (baseService, info) =>
        {
          var msg = string.Empty;
          var tableName = TableAtributeUtil.GetTable<Menu>();
          var sql = string.Empty;
          if (string.Compare(type, "-9") == 0)
          {
            sql = $"update {tableName} set status=-9 where parentId=@parentId;";
          }
          else
          {
            sql = $"delete from {tableName} where parentId=@parentId;";
          }
          baseApplication.mySqlSugar.ExecuteSql(sql, new { parentId = Id }, out msg);
          UserAuthorCache.AddAuthorcache(baseApplication.mySqlSugar, true, true);
        }
      );
    }

    /// <summary>
    /// 还原用户角色菜单删除信息
    /// </summary>
    /// <param name="Id"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> Reduction(string Id, string loginUserCode)
    {
      return await baseApplication.Reduction<Menu>(
        Id,
        loginUserCode,
        BusinessType.menu,
        (a, b, info) =>
        {
          return info.aName + "|" + info.aCode;
        },
        (db, data) =>
        {
          UserAuthorCache.AddAuthorcache(baseApplication.mySqlSugar, true, true);
        }
      );
    }

    /// <summary>
    /// 绑定用户角色菜单信息
    /// </summary>
    /// <param name="uId"></param>
    /// <param name="rId"></param>
    /// <param name="aIds"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddResourceToUser(
      string uId,
      string rId,
      string aIds,
      string loginUserCode
    )
    {
      return await baseApplication.DoAction(
        BusinessType.user,
        BusinessActionType.update,
        BusinessLogType.writeLogToDataBase,
        loginUserCode,
        "用户编号：" + uId + "|角色编号：" + rId + "|菜单编号：" + aIds,
        "绑定用户角色菜单信息",
        (mySqlSugar) =>
        {
          CommonResult result = new CommonResult();
          string msg = string.Empty;
          var sql = string.Empty;
          var tableName = TableAtributeUtil.GetTable<URPermission>();
          var LoginCode = HttpContextExtendBase.GetLoginCode();
          var LoginAppid = HttpContextExtendBase.GetLoginAppid();
          if (
            string.Compare(LoginCode, "ajng", true) != 0
            && string.Compare(LoginAppid, "admin", true) != 0
          )
          {
            result.msg = ImplementResult.Nopermissiontooperate.GetRemark();
            return result;
          }
          if (
            (string.IsNullOrEmpty(uId) || string.IsNullOrEmpty(rId)) && string.IsNullOrEmpty(aIds)
          )
          {
            result.msg = ImplementResult.ParameterException.GetRemark();
            return result;
          }

          if (
            !string.IsNullOrEmpty(uId)
            && !string.IsNullOrEmpty(rId)
            && string.IsNullOrEmpty(aIds)
          )
          {
            sql = $"delete from {tableName}  where uId={uId} and rId={rId};";
            mySqlSugar.ExecuteSql(sql, null, out msg);
            result.msg = msg;
            return result;
          }
          List<string> newids = aIds.Split(',').ToList();
          var author = TableAtributeUtil.GetTable<Menu>();
          sql =
            $"select Id,aType,aName,aParentId from {author} where Id in({aIds}) and status<>-9;";
          var authorlist = baseApplication.mySqlSugar.Query<Menu>(sql, null, out msg);
          if (string.IsNullOrEmpty(msg) && authorlist != null && authorlist.Count == 0)
          {
            result.msg = ImplementResult.ParameterException.GetRemark();
            return result;
          }
          sql = $"select * from {tableName}  where uId={uId} and rId={rId};";
          var list = baseApplication.mySqlSugar.Query<URPermission>(sql, null, out msg);
          if (string.IsNullOrEmpty(msg))
          {
            if (list != null)
            {
              //var authorcachelist = UserAuthorCache.GetMenucache();
              //foreach (var item in authorlist)
              //{
              //    var plist = authorcachelist
              //        .Where(o => o.Id == item.aParentId)
              //        .ToList();
              //    if (string.IsNullOrEmpty(msg) && plist != null && plist.Count > 0)
              //    {
              //        var pdata = plist.FirstOrDefault();
              //        if (!newids.Contains(pdata.Id.ToString()))
              //        {
              //            newids.Add(pdata.Id.ToString());
              //        }
              //    }
              //}
              //sql =
              //    $"select Id,aName,aParentId,status,cTime from {author} where Id in({aIds}) and aType=2 and status<>-9 and (ISNULL(ahtmlUrl) or ahtmlUrl='' or ahtmlUrl='/' or ahtmlUrl='/null')";
              //var modulelist = baseApplication.mySqlDapper.Query<Menu>(
              //    sql,
              //    null,
              //    out msg
              //);
              //if (
              //    string.IsNullOrEmpty(msg)
              //    && modulelist != null
              //    && modulelist.Count > 0
              //)
              //{
              //    foreach (var item in modulelist)
              //    {
              //        if (!newids.Contains(item.Id.ToString()))
              //        {
              //            newids.Add(item.Id.ToString());
              //        }
              //    }
              //}
              //aIds = String.Join(",", newids);
              if (list.Count > 0)
              {
                sql = $"update {tableName} set aIds='{aIds}' where uId={uId} and rId={rId};";
                baseApplication.mySqlSugar.ExecuteSql(sql, null, out msg);
              }
              else
              {
                URPermission uRPermission = new URPermission()
                {
                  uId = uId.GetIntValue(),
                  rId = rId.GetIntValue(),
                  aIds = aIds,
                  status = 1
                };
                baseApplication.mySqlSugar.Insert(uRPermission, out msg);
                result.msg = msg;
              }
              UserAuthorCache.AddURMcache(baseApplication.mySqlSugar, true, true);
            }
            else
            {
              result.msg = ImplementResult.ParameterException.GetRemark();
            }
          }
          else
          {
            result.msg = msg;
          }
          return result;
        }
      );
    }

    /// <summary>
    /// 绑定角色菜单信息
    /// </summary>
    /// <param name="rId"></param>
    /// <param name="aIds"></param>
    /// <param name="loginUserCode"></param>
    /// <returns></returns>
    public async Task<CommonResult> AddResourceToRole(string rId, string aIds, string loginUserCode)
    {
      return await baseApplication.DoAction(
        BusinessType.user,
        BusinessActionType.update,
        BusinessLogType.writeLogToDataBase,
        loginUserCode,
        "角色编号：" + rId + "|菜单编号：" + aIds,
        "绑定用户角色菜单信息",
        (baseService) =>
        {
          CommonResult result = new CommonResult();
          string msg = string.Empty;
          string sql = string.Empty;
          var tableName = TableAtributeUtil.GetTable<RoleResource>();
          var LoginCode = HttpContextExtendBase.GetLoginCode();
          var LoginAppid = HttpContextExtendBase.GetLoginAppid();
          if (
            string.Compare(LoginCode, "ajng", true) != 0
            && string.Compare(LoginAppid, "admin", true) != 0
          )
          {
            result.msg = ImplementResult.Nopermissiontooperate.GetRemark();
            return result;
          }
          if (string.IsNullOrEmpty(rId) && string.IsNullOrEmpty(aIds))
          {
            result.msg = ImplementResult.ParameterException.GetRemark();
            return result;
          }
          if (!string.IsNullOrEmpty(rId) && string.IsNullOrEmpty(aIds))
          {
            sql = $"delete from {tableName}  where rId={rId};";
            baseService.ExecuteSql(sql, null, out msg);
            result.msg = msg;
            return result;
          }
          List<string> newids = aIds.Split(',').ToList();
          var author = TableAtributeUtil.GetTable<Menu>();
          sql =
            $"select Id,aType,aName,aParentId from {author} where Id in({aIds}) and status<>-9;";
          var authorlist = baseApplication.mySqlSugar.Query<Menu>(sql, null, out msg);
          if (string.IsNullOrEmpty(msg) && authorlist != null && authorlist.Count == 0)
          {
            result.msg = ImplementResult.ParameterException.GetRemark();
            return result;
          }
          aIds = String.Join(",", newids);
          sql = $"select * from {tableName}  where rId={rId};";
          var list = baseService.Query<RoleResource>(sql, null, out msg);
          if (string.IsNullOrEmpty(msg))
          {
            if (list.Count > 0)
            {
              sql = $"update {tableName} set aIds='{aIds}' where rId={rId};";
              baseService.ExecuteSql(sql, null, out msg);
              result.msg = msg;
            }
            else
            {
              RoleResource uRPermission = new RoleResource()
              {
                rId = rId.GetIntValue(),
                aIds = aIds,
                status = 1
              };
              baseService.Insert(uRPermission, out msg);
              result.msg = msg;
            }
            UserAuthorCache.AddRoleRescache(baseApplication.mySqlSugar, true, true);
          }
          else
          {
            result.msg = ImplementResult.ParameterException.GetRemark();
          }
          return result;
        }
      );
    }

    /// <summary>
    /// 获取用户角色权限菜单
    /// </summary>
    /// <param name="rId"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetRoleResource(string rId, string loginUserCode)
    {
      return await baseApplication.DoAction(
        BusinessType.menu,
        BusinessActionType.update,
        BusinessLogType.writeLogToDataBase,
        loginUserCode,
        rId,
        "获取用户角色权限菜单",
        (baseService) =>
        {
          CommonResult result = new CommonResult();
          var tableName = TableAtributeUtil.GetTable<Menu>();
          string sql = string.Format(" where 1=1 and aType=1");
          MenuQuery MenuQuery = new MenuQuery()
          {
            tableName = tableName,
            sqlWhere = sql,
            sortFile = "Id",
            sortType = "desc",
            files = "*",
            pageIndex = 1,
            pageSize = 30,
          };
          string msg = string.Empty;
          List<Menu> moduleList = new List<Menu>();
          long totalCount = 0;
          //获取角色模块信息
          baseService.GetList(MenuQuery, out msg, out moduleList, out totalCount);
          if (string.IsNullOrEmpty(msg))
          {
            result.data = moduleList;
          }
          else
          {
            result.msg = msg;
            result.code = (int)CodeResult.fail;
          }
          return result;
        }
      );
    }

    /// <summary>
    /// 获取省市县信息
    /// </summary>
    /// <param name="mySqlBase"></param>
    /// <returns></returns>
    public async Task<CommonResult> GetCity(IMySqlSugarService mySqlBase)
    {
      return await Task.Factory.StartNew(() =>
      {
        CommonResult result = new CommonResult();
        List<CityExtend> list = new List<CityExtend>();
        if (QueryCacheUtil<CityExtend>.IsExists("cityall"))
        {
          list = QueryCacheUtil<CityExtend>.GetData("cityall").data;
          result.data = list;
          result.count = list.Count;
          return result;
        }
        var table = TableAtributeUtil.GetTable<City>();
        var sql = $"select * from {table};";
        var data = mySqlBase.Query<City>(sql, out var msg);
        var pdata = data.Where(o => o.class_type == 1 && o.class_name == "广东省");
        var cdata = data.Where(o => o.class_type == 2 && o.class_name == "广州市");
        var adata = data.Where(o => o.class_type == 3);
        foreach (var item in pdata)
        {
          var padata = cdata.Where(o => o.class_parent_id == item.class_id).ToArray();
          var pcity = padata.MapToList<CityModel, City>(pd =>
          {
            pd.ForMember(d => d.label, opt => opt.MapFrom(s => s.class_name));
            pd.ForMember(d => d.value, opt => opt.MapFrom(s => s.class_id));
          });
          CityExtend cityExtend = new CityExtend()
          {
            label = item.class_name,
            value = item.class_id.ToString(),
            isLeaf = false
          };
          var citydata = pcity.ToArray();
          foreach (var itemb in citydata)
          {
            var pbdata = adata.Where(o => o.class_parent_id == itemb.value.GetIntValue()).ToArray();
            var paity = pbdata.MapToList<CityModel, City>(pd =>
            {
              pd.ForMember(d => d.label, opt => opt.MapFrom(s => s.class_name));
              pd.ForMember(d => d.value, opt => opt.MapFrom(s => s.class_id));
              pd.ForMember(d => d.isLeaf, opt => opt.MapFrom(s => s.class_type == 3));
            });
            var paddata = paity.ToArray();
            itemb.children = paddata; // 城市对应的县区集合
          }
          cityExtend.children = citydata; // 省份对应的城市集合
          list.Add(cityExtend);
        }
        result.data = list;
        result.count = list.Count;
        QueryCache<CityExtend> queryCache = new QueryCache<CityExtend>() { data = list };
        QueryCacheUtil<CityExtend>.AddData("cityall", queryCache);
        return result;
      });
    }
  }
}
